import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { getToken } from "@/utils/auth";
import qs from "qs";
import { ElMessage } from "element-plus";
// 创建 axios 实例
const service = axios.create({
  baseURL: "/proxy",
  timeout: 50000,
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.paramsSerializer = (params) => {
      return qs.stringify(params, { arrayFormat: "repeat", encode: true });
    };
    const isToken = (config.headers || {}).isToken === false;
    if (getToken() && !isToken) {
      config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers.Accept = "application/json";
    config.headers["Content-Type"] = "application/json";
    config.headers["X-Requested-With"] = "XMLHttpRequest";
    if (!config.data) config.data = {};
    return config;
  },
  (error: any) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse) => {
    const contentType = res.headers["content-type"];
    if (
      contentType.indexOf(
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      ) != -1
    ) {
      return res.data;
    }
    return Promise.resolve(res.data);
  },
  (error: any) => {
    const { response } = error;
    const { data } = response || {};
    // 处理请求错误的返回结果
    const errorObj = {
      status: response?.status,
      statusText: response?.statusText,
      errorCode: data?.errorCode ?? data?.error ?? data?.code,
      errorMessage: data?.errorMessage ?? data?.message ?? data?.error ?? data,
    };
    if (response && response.status === 401) {
      console.error("登录超时", response);
      const loginUrl = response?.headers?.loginurl || "";

      if (loginUrl) {
        // 跳转登录页
        window.location.href = loginUrl;
        return Promise.reject(errorObj);
      } else {
        // 页面刷新
        window.location.href = "/login";
        return Promise.reject(errorObj);
      }
    }
    ElMessage.error(errorObj.errorMessage);
    return Promise.resolve(errorObj);
  }
);

// 导出 axios 实例
export default service;
